<template>
  <div>
    <h2>蓝牙设备连接</h2>
    <button @click="scanDevices">扫描设备</button>
    <ul>
      <li v-for="device in devices" :key="device.address">
        {{ device.name }} ({{ device.address }})
        <button @click="connect(device.address)">连接</button>
      </li>
    </ul>

    <div v-if="connectedDevice">
      <h3>已连接: {{ connectedDevice.name }}</h3>
      <button @click="disconnect">断开连接</button> <!-- 💥 新增断开按钮 -->
      <input v-model="sendDataInput" placeholder="输入要发送的内容"/>
      <button @click="send">发送</button>
      <div><strong>收到数据:</strong> {{ receivedData }}</div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {bluetooth} from '@/composable/bluetoothService'
import {getStorage, setStorage} from "@/utools/storeage.js";

const devices = ref([])
const connectedDevice = ref(null)
const receivedData = ref('')
const sendDataInput = ref('')

async function scanDevices() {
  try {
    const pairedDevices = await bluetooth.checkBluetoothAndListDevices()
    devices.value = pairedDevices
  } catch (err) {
    alert('扫描失败: ' + err.message)
  }
}

async function connect(address) {
  try {
    await bluetooth.connectToDevice(address)
    connectedDevice.value = devices.value.find(d => d.address === address)
    bluetooth.listenForData(data => {
      receivedData.value += data
    })
    setStorage('lastConnectedDeviceAddress', address)
  } catch (err) {
    console.error('【蓝牙连接失败】错误详情:', err) // 🔍 Log 1: 错误对象详情
    console.log('【蓝牙连接失败】尝试连接的设备地址:', address) // 📍 Log 2: 当前尝试连接的设备地址

    alert('连接失败: ' + err.message)
  }
}

async function disconnect() {
  if (!connectedDevice.value) return;

  try {
    await bluetooth.disconnect(); // 调用蓝牙服务的断开方法
    alert('蓝牙已断开');
    connectedDevice.value = null; // 更新 UI 状态
  } catch (err) {
    console.error('【蓝牙断开失败】错误详情:', err);
    alert('断开失败: ' + err.message);
  }
}

async function send() {
  if (!sendDataInput.value) return
  try {
    await bluetooth.sendData(sendDataInput.value + '\n') // 添加换行符作为结束标志
  } catch (err) {
    alert('发送失败: ' + err.message)
  }
}

onMounted(async () => {
  try {
    const pairedDevices = await bluetooth.checkBluetoothAndListDevices()
    devices.value = pairedDevices

    const address = getStorage('lastConnectedDeviceAddress')
    if (!address) {
      console.log('⚠️ 没有找到上次连接的设备')
      return
    }

    // 👇 先检查当前是否已经连接
    const isActuallyConnected = await bluetooth.isConnected()
    if (isActuallyConnected) {
      console.log('✅ 设备实际上已连接，更新 UI')
      connectedDevice.value = pairedDevices.find(d => d.address === address)
      bluetooth.listenForData(data => {
        receivedData.value += data
      })
      return
    }

    // 如果未连接，则尝试重新连接
    setTimeout(async () => {
      try {
        await bluetooth.connectToDevice(address)
        connectedDevice.value = pairedDevices.find(d => d.address === address)
        bluetooth.listenForData(data => {
          receivedData.value += data
        })
      } catch (err) {
        console.error('❌ 【自动连接失败】:', err)
        setStorage('lastConnectedDeviceAddress', null)
        connectedDevice.value = null
      }
    }, 800)

  } catch (err) {
    console.error('【蓝牙初始化失败】:', err)
    alert('蓝牙初始化失败: ' + err.message)
    connectedDevice.value = null
  }
})

</script>
